//
//  LoginViewController.m
//  Student
//
//  Created by 李飞 on 15/9/8.
//  Copyright (c) 2015年 XueYinYue. All rights reserved.
//

#import "LoginViewController.h"
#import "NSString+WPAttributedMarkup.h"
#import <CoreText/CoreText.h>
#import "RDVTabBarController.h"

#import "RegisterViewController.h"
#import "ForgetPasswordViewController.h"

#import "UserBSGetVerificationCode.h"
#import "UserBSLoginWithVerification.h"
#import "UserBSLoginWithPassWord.h"
#import "HomeViewController.h"
#import "MyInfoViewController.h"


@interface LoginViewController ()
{
    int _timeout;
    dispatch_source_t _timer;
    bool isPasswordLogin;
    bool isPhoneNull;
    bool isPasswordNull;
}

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.rdv_tabBarController.tabBarHidden = YES;
   // self.title = @"用户短信验证登录";
    isPasswordLogin = NO;
    
    isPhoneNull = YES;
    isPasswordNull = YES;
    _verificationCode = @"";
    
    
    _passwordShortView.hidden = NO;
    _passwordLongView.hidden = YES;
    _showPasswordBtn.hidden = YES;
    _loginBtn.enabled = NO;
    
    //设置TFplaceholder字体颜色
    [_userNameTF setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_identifyCodeTF setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    
   [self initNavegationBar];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/**
 *  创建改变获取验证码按钮状态的定时器
 */
- (void)createTimer
{
    _timeout = 60;
    dispatch_queue_t queue = dispatch_queue_create("timer queue", 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_timer, ^{
        if (_timeout > 0)
        {
            _timeout -= 1;
            dispatch_async(dispatch_get_main_queue(), ^{
                [_getVerificationCodeButton setTitle:[NSString stringWithFormat:@"获取验证码(%ds)",_timeout] forState:UIControlStateDisabled];
                [_getVerificationCodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                _getVerificationCodeButton.enabled = YES;
                [_getVerificationCodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [_getVerificationCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
            });
            dispatch_source_cancel(_timer);
        }
    });
    dispatch_source_set_cancel_handler(_timer, ^{
        //        NSLog(@"timer cancle");
        _timer = nil;
    });
    dispatch_resume(_timer);
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    
    if( textField == _userNameTF)
    {
        if (toBeString.length != 0)
        {
            isPhoneNull = NO;
        }
        else
        {
            isPhoneNull = YES;
        }
    }
    
    if ( textField == _identifyCodeTF)
    {
        if (toBeString.length != 0)
        {
            isPasswordNull = NO;
        }
        else
        {
            isPasswordNull = YES;
        }
    }
    
    
    if (isPasswordNull || isPhoneNull )
    {
        _loginBtn.enabled = NO;
    }
    else
    {
        _loginBtn.enabled = YES;
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark -  事件响应

- (IBAction)onReceiveIdentifyingCodeButtonClick:(id)sender {

    UserBSGetVerificationCode *userBSGetVerificationCode = [[UserBSGetVerificationCode alloc] init];
    userBSGetVerificationCode.username = _userNameTF.text;
    
    [self showProgressView];
    [self runService:userBSGetVerificationCode andComplete:^(EACService *service) {
        [self hideProgressView];
    } andSuccess:^(EACService *service, id o) {
        UserBSGetVerificationCodeResult* userBSGetVerificationCodeResult = o;
        if (userBSGetVerificationCodeResult.isSuccess)
        {
            _getVerificationCodeButton.enabled = NO;
            _verificationCode = userBSGetVerificationCodeResult.code;
            
            if (!_timer)
            {
                [self createTimer];
            }
        }
        else
        {
            SHOW_ALERTVIEW(@"提示", userBSGetVerificationCodeResult.message, 1, self);
        }
    } ];
    

}

- (IBAction)onLoginbuttonClick:(id)sender {
    
    
    if (isPasswordLogin)
    {
        //密码登陆
        UserBSLoginWithPassWord *userBSLoginWithPassWord = [[UserBSLoginWithPassWord alloc] init];
        userBSLoginWithPassWord.userName = _userNameTF.text;
        userBSLoginWithPassWord.password = _identifyCodeTF.text;
        
        [self showProgressView];
        [self runService:userBSLoginWithPassWord andComplete:^(EACService *service) {
            [self hideProgressView];
        } andSuccess:^(EACService *service, id o) {
            UserBSLoginWithPassWordResult* userBSLoginWithPassWordResult = o;
            
            if (userBSLoginWithPassWordResult.isLoginSuccess)
            {
                if(userBSLoginWithPassWordResult.isGotoUserInfo)
                {
                    HomeViewController *homeViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
                    [self.navigationController pushViewController:homeViewController animated:YES];
                }
                else
                {
                    MyInfoViewController *myInfoViewController = [[MyInfoViewController alloc] initWithNibName:@"MyInfoViewController" bundle:nil];
                    myInfoViewController.isComeHome = NO;
                    [self.navigationController pushViewController:myInfoViewController animated:YES];
                }

            }
            else
            {
                SHOW_ALERTVIEW(@"提示", userBSLoginWithPassWordResult.message, 1, self);
            }
        }];
        
    }
    else
    {
        //验证码登陆
        UserBSLoginWithVerification *userBSLoginWithVerification = [[UserBSLoginWithVerification alloc] init];
        userBSLoginWithVerification.username = _userNameTF.text;
        userBSLoginWithVerification.getVerificationCode = _verificationCode;
        userBSLoginWithVerification.InputVerificationCode = _identifyCodeTF.text;
        
        [self showProgressView];
        [self runService:userBSLoginWithVerification andComplete:^(EACService *service) {
            [self hideProgressView];
        } andSuccess:^(EACService *service, id o) {
            UserBSLoginWithVerificationResult* userBSLoginWithVerificationResult = o;
            
            if (userBSLoginWithVerificationResult.isLoginSuccess)
            {
                
                if(userBSLoginWithVerificationResult.isGotoUserInfo)
                {
                    HomeViewController *homeViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
                    [self.navigationController pushViewController:homeViewController animated:YES];
                }
                else
                {
                    MyInfoViewController *myInfoViewController = [[MyInfoViewController alloc] initWithNibName:@"MyInfoViewController" bundle:nil];
                    myInfoViewController.isComeHome = NO;
                    [self.navigationController pushViewController:myInfoViewController animated:YES];
                }

            }
            else
            {
                SHOW_ALERTVIEW(@"提示", userBSLoginWithVerificationResult.message, 1, self);
            }
        }];
        
    }
    
}

#pragma mark -  忘记密码
- (IBAction)onForgetPasswordClick:(id)sender {
    
    ForgetPasswordViewController *forgetPasswordViewController = [[ForgetPasswordViewController alloc] initWithNibName:@"ForgetPasswordViewController" bundle:nil];
    [self.navigationController pushViewController:forgetPasswordViewController animated:YES];
}

#pragma mark -  改变登录模式
- (IBAction)onChangeLoginStyeClick:(id)sender {
    isPasswordLogin = !isPasswordLogin;
    [_identifyCodeTF setText:@""];
    if (isPasswordLogin) {
        [_changeLoginStyleBtn setTitle: @"验证码登录" forState:UIControlStateNormal];
        _getVerificationCodeButton.hidden = YES;
        _identifyCodeTF.placeholder = @"请输入登录密码";
        _identifyCodeTF.secureTextEntry = YES;
        _identifyCodeTF.keyboardType = UIKeyboardTypeDefault;
        _passwordShortView.hidden = YES;
        _passwordLongView.hidden = NO;
        _showPasswordBtn.hidden = NO;
    }
    else{
        [_changeLoginStyleBtn setTitle:@"账号登录" forState:UIControlStateNormal];
        
        _getVerificationCodeButton.hidden = NO;
        _passwordShortView.hidden = NO;
        _passwordLongView.hidden = YES;
        _identifyCodeTF.placeholder = @"请输入验证码";
        _identifyCodeTF.keyboardType = UIKeyboardTypeNumberPad;
        _showPasswordBtn.hidden = YES;
    }
}

#pragma mark -  隐藏显示密码
- (IBAction)onShowPasswordClick:(id)sender {
    UIImage *image;
    _identifyCodeTF.secureTextEntry = !_identifyCodeTF.isSecureTextEntry;
    if (_identifyCodeTF.secureTextEntry)
    {
        image = [UIImage imageNamed:@"icon_eye_gray.png"];
    }
    else
    {
        image = [UIImage imageNamed:@"icon_eye_green.png"];
    }
    [_showPasswordBtn setImage:image forState:UIControlStateNormal];
}
#pragma mark -  NavegationBar

- (void)initNavegationBar
{
    
    //    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    //    backBtn.bounds = CGRectMake(0, 0, 15, 20);
    //    [backBtn addTarget:self action:@selector(onBackButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    //    [backBtn setBackgroundImage:[UIImage imageNamed:NAVIGATION_BACKARROW_IMAGE] forState:UIControlStateNormal];
  
    UIBarButtonItem *registerBarBtn = [[UIBarButtonItem alloc] initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(onRegisterButtonClick:)];
 //   self.navigationItem.leftBarButtonItem = backBarBtn;
    
    self.navigationItem.rightBarButtonItem = registerBarBtn;
}

- (void)onRegisterButtonClick:(id)sender
{
    RegisterViewController *registerViewController = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
    [self.navigationController pushViewController:registerViewController animated:YES];
}

- (void)onBackButtonClick:(id)sender
{
   [self.navigationController popViewControllerAnimated:YES];
}

@end
